<template>
  <el-tree
    ref="tree"
    class="department-screen"
    :data="tree"
    :props="{
      children: 'children',
      label: 'label'
    }"
    node-key="id"
    :indent="4"
    :default-expand-all="true"
    :current-node-key="curNode.id"
    @node-click="nodeClick"
    :expand-on-click-node="false"
    v-loading="loading"
  />
</template>
<script>
export default {
  name: 'department-screen',
  data () {
    return {
      tree: [],
      loading: true,
      curNode: {
        children: [],
        id: null
      }
    }
  },
  created () {
    this.getDepartments()
  },
  methods: {
    getDepartments () {
      this.tree = []
      let curNode = this.$refs.tree && this.$refs.tree.getCurrentNode()
      this.$GET('sot-admin-api/sys/department/tree')
        .then(res => {
          this.tree = res.data || []
          this.$emit('update:treeData', this.tree)
          if (this.tree.length > 0) {
            curNode = curNode || this.tree[0]
            this.nodeClick(curNode)
            this.$nextTick(() => {
              if (this.$refs.tree) {
                this.$refs.tree.setCurrentNode(curNode)
              }
            })
          }
        })
        .finally(_ => {
          this.loading = false
        })
    },
    nodeClick (curNode) {
      this.curNode = curNode
      let id = curNode.id
      this.$emit('input', id)
      this.$emit('change', id)
      this.$emit('update:curNode', curNode)
    }
  }
}
</script>

<style lang="scss">
.department-screen {
  width: 260px;
  overflow: hidden;
  padding: 20px;
  padding-right: 0;
  background-color: transparent;
  .el-tree-node {
    margin: 0;
  }
  .el-tree-node__content {
    padding: 6px 0;
    height: auto;
  }

  .el-tree-node.is-current > .el-tree-node__content {
    background-color: rgba(173, 216, 230, 0.2);
  }

  .el-tree-node__label {
    font-size: 16px !important;
  }
}
</style>
